$(document).ready(bindKeys);

var flag = 0;

var options = {
bars: { show: true, barWidth: 0.5, fill: 0.9 },

	lines: { show: true },
	points: { show: true },
	xaxis: { tickDecimals: 0, tickSize: 1, min: 0, max: 60 }
};
var xvalue = 0;
var data = [];
var placeholder = $("#placeholder");

function bindKeys() {
	$(document).bind('keydown', 'left', onLeftPress);
	$(document).bind('keydown', 'right', onRightPress);
	
	setFlag();
	initChart();
}

function initChart() {
    placeholder = $("#placeholder");
	$.plot(placeholder, data, options);

}

function setFlag() {
	flag = Math.floor(Math.random()*2);
}

function checkFlag(value) {
	//alert( "Flag="+flag+", value="+value);
	if ( flag == value) {
		addBlock();
		plotChart(6);
	} else {
		removeBlock();
		plotChart(0);
	}
}

function addBlock() {
	$("ul#tower").append('<li>tower block</li>');
}

function removeBlock() {
	$("ul#tower li:last").remove();
}

function onLeftPress() {
	checkFlag(0);
	setFlag();
}

function onRightPress() {
	checkFlag(1);
	setFlag();
}

function plotChart(yvalue) {

	data.push( [xvalue++, yvalue]);
	var obj = $.plot($("#placeholder"), [data], options); 
	
	if (xvalue >= 60) {
		options = {
			bars: { show: true, barWidth: 0.5, fill: 0.9 },
			lines: { show: true },
			points: { show: true },
			xaxis: { tickDecimals: 0, tickSize: 1, min: xvalue-60, max: xvalue }
		};
	}
	obj.setupGrid();
	obj.draw();

}